package com.lance.answer.gui.answer;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.lance.answer.dto.CompleteInfo;
import com.lance.answer.dto.Item;
import com.lance.answer.gui.answer.gk.DealInfoUtil;
import com.lance.answer.util.Constant;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.Select;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;

public class Util {

   public static Map<String,String> DataConvert = Maps.newHashMap();

   public static List<String> getVip(){
      return Lists.newArrayList(
             // "2051001463552"
           //   "2113001252793"
              //"2113001209166",
          //    "2161001202162"
              //"2051001463552"
//              "1934001257189",
//              "2165001455550",
           //   "2037106456405"
//              "2165001467446",
//              "2165001467461",
              "1542101400128",
              "2152001450663",
              "2122001451888",
              "1951001460872",
              "2162001251213",
              "2162001251218",
              "2161101201214"
       //       "2151001460863"
             // "2111001200703"


      );
   }

    public static void main(String[] args) throws Exception{




        Map<String, List<String>>  countUserCourseInfo =  DealInfoUtil.countUserCourseInfo("libs//userCourseInfo");
        int sum = 0;
//        for(String subjectName:countUserCourseInfo.keySet()){
//            if(!new File("D:\\project\\answer-tool\\src\\main\\resources\\"+subjectName + "/" + subjectName + "-answer.json").exists()){
//                continue;
//            }
//            sum +=countUserCourseInfo.get(subjectName).size();
//        }

        Set<String> set = Sets.newHashSet();
        for(File directory:new File("libsTmp//answerInfo").listFiles()){
     //   for(File directory:new File("libs//answerInfo").listFiles()){

            for(File file:directory.listFiles()){
                String REGEX = "[^(0-9)]";
                String fileName = file.getName();
                fileName = Pattern.compile(REGEX).matcher(fileName).replaceAll("").trim();
                set.add(directory.getName()+fileName);
            }
        }

        System.err.println("所有课程加起来为："+sum);
        System.err.println("所有课程加起来为111："+set.size());
        Thread.sleep(2000000);



        System.err.println(Integer.parseInt("03324"));
        String s = "http://xinjiang.ouchn.cn/pluginfile.php/463033/question/answer/5301464/20/1172159/01.png";
        System.err.println(s.substring(s.lastIndexOf("/")));
        System.err.println(DealInfoUtil.countUserCourseInfo("libs//userCourseInfo").get("理工英语3"));
        System.err.println(DealJsonString.saveZhWord("试题正文\n填空题12、中国近现代学前教育理论流派的特点是学习借鉴\n回答\n\n\n，探索\n回答\n\n\n\n的学前教育理论。"));
        System.err.println(getTime("00:20:05"));
    }

    static {

        DataConvert.put("A.","0");
        DataConvert.put("A","0");
        DataConvert.put("a.","0");
        DataConvert.put("a","0");
        DataConvert.put("B.","1");
        DataConvert.put("B","1");
        DataConvert.put("b.","1");
        DataConvert.put("b","1");
        DataConvert.put("C.","2");
        DataConvert.put("C","2");
        DataConvert.put("c.","2");
        DataConvert.put("c","2");
        DataConvert.put("D.","3");
        DataConvert.put("D","3");
        DataConvert.put("d.","3");
        DataConvert.put("d","3");
        DataConvert.put("E.","4");
        DataConvert.put("E","4");
        DataConvert.put("T","0");
        DataConvert.put("F","1");
    }


    public static ChromeDriver getDriver(String driverPath) {
        //System.setProperty("webdriver.chrome.driver", "c:\\ynouAutoStudy\\chromedriver.exe");
        if (StringUtils.isNotBlank(driverPath)) {
            System.setProperty("webdriver.chrome.driver",driverPath);
        }

        //代理
        /*BrowserMobProxy proxy = new BrowserMobProxyServer();
        proxy.start(0);

        // get the Selenium proxy object
        Proxy seleniumProxy = ClientUtil.createSeleniumProxy(proxy);

        // configure it as a desired capability
        DesiredCapabilities capabilities = new DesiredCapabilities();
        capabilities.setCapability(CapabilityType.PROXY, seleniumProxy);*/
        ChromeOptions options = new ChromeOptions();
        //防止被识别
        options.setExperimentalOption("excludeSwitches", Collections.singletonList("enable-automation"));
        options.setExperimentalOption("useAutomationExtension", false);
        //关闭使用ChromeDriver打开浏览器时上部提示语"Chrome正在受到自动软件的控制"
        options.addArguments("disable-infobars");

        Map<String,Object> command = new HashMap<>();
        command.put("source","Object.defineProperty(navigator, 'webdriver', {get: () => undefined})");
        ChromeDriver webDriver = new ChromeDriver(options);
        webDriver.executeCdpCommand("Page.addScriptToEvaluateOnNewDocument",command);
        return webDriver;
    }


    public static void switchToLast(WebDriver driver) {
        Set<String> windowHandles = driver.getWindowHandles();
        List<String> list = new LinkedList<>(windowHandles);
        driver.switchTo().window(list.get(list.size() - 1));
    }

    public static void switchToUrl(WebDriver driver,String url) {
        Set<String> windowHandles = driver.getWindowHandles();
        for (String str:windowHandles) {
            if (url.trim().equalsIgnoreCase(str.trim())) {
                driver.switchTo().window(str);
                return;
            }
        }
        driver.switchTo().window(windowHandles.toArray()[0].toString());
    }

    public static void switchToFirst(WebDriver driver) {
        Set<String> windowHandles = driver.getWindowHandles();
        List<String> list = new LinkedList<>(windowHandles);
        driver.switchTo().window(list.get(0));
    }



    /**
     * 将字符串的时间转成秒数
     * @param s 字符串时间 06：03
     * @return 秒数
     */
    public static int getTime(String s){
        int time = 0;
        try {
            String[] array = s.split(":");
            int i =array.length-1;
            for(String a:array){
                time += Math.pow(60,i)*Integer.parseInt(a);
                i--;
            }

        }catch (Exception e){
            e.printStackTrace();
        }
        return time;
    }


    /**
     * 登录
     * @param driver driver
     * @param username username
     * @param password password
     */
    public static void login(WebDriver driver, String username, String password) throws InterruptedException {
       /* driver.findElement(By.id("username")).sendKeys(new String[]{username});
        driver.findElement(By.id("password")).sendKeys(new String[]{password});
        *//*WebElement loginBtn = driver.findElement(By.id("loginbtn"));
        loginBtn.click();*//*
        for (WebElement element : driver.findElements(By.tagName("button"))) {
            if ("登录".equals(element.getText())) {
                element.click();
            }
        }*/
        //TimeUnit.SECONDS.sleep(1);
        WebElement agreeButton = driver.findElement(By.id("RememberLogin"));

        agreeButton.click();
        //TimeUnit.SECONDS.sleep(1);

        WebElement userNameInput = driver.findElement(By.id("username"));
        userNameInput.clear();
        userNameInput.sendKeys(username);
        //TimeUnit.SECONDS.sleep(1);

        WebElement passwordInput = driver.findElement(By.id("password"));
        passwordInput.clear();
        passwordInput.sendKeys(password);
        //TimeUnit.SECONDS.sleep(1);

        //webDriverWait.until(ExpectedConditions.elementToBeClickable(By.id("loginId"))).sendKeys(username);

        WebElement loginBtn = driver.findElement(By.name("button"));

        loginBtn.click();



        //Cookie cookie = new Cookie("MoodleSession","vc7r1v0nb3q7gi2tvir37d6n21");
        //chromeDriver.manage().addCookie(cookie);
        //System.out.println(chromeDriver.manage().getCookies().toString());

        TimeUnit.SECONDS.sleep(3);

        //System.out.println(driver.manage().getCookies().toString());

        //chromeDriver.navigate().refresh();
        driver.get("http://student.ouchn.cn/#/home");

        Set<Cookie> cookies = null;
        int count = 0;
        do{
            //System.out.println("获取token第" + count  + "次 ");
            try {
                cookies = driver.manage().getCookies();
                Thread.sleep(Constant.TIMEOUT * 1000);
            } catch (InterruptedException e2) {
                e2.printStackTrace();
            }catch (Exception e3){
                e3.printStackTrace();
            }
        }while(cookies == null);
        //System.out.println(cookies);
        TimeUnit.SECONDS.sleep(2);
    }

    /**
     * 获取用户的Cookie
     * @param set set
     * @return 用户
     */
    public static String getCookie( Set<Cookie> set){
        StringBuilder sb = new StringBuilder();
        for (Cookie c : set) {
            sb.append(c.getName());
            sb.append("=");
            sb.append(c.getValue());
            sb.append("; ");
        }
        String cookie = sb.toString();
        return cookie.substring(0,cookie.length()-2);
    }

    /**
     * 将cookie里面的XSKJ-AdminBasicTest2AndSave-Struct提取出来封装成header里面的参数
     * @param set cookie集合
     * @return studentSpaceProfile
     */
    public static String getStudentSpaceProfile( Set<Cookie> set){
        String studentSpaceProfile = "";
        for (Cookie c : set) {
            // XS:学生 JS:教师
           // if ("XSKJ-AdminBasicTest2AndSave-Struct" .equals(c.getName())) {
            if ("JSKJ-Admin-Struct" .equals(c.getName())) {
                studentSpaceProfile = c.getValue();
                studentSpaceProfile = studentSpaceProfile.replaceAll("%25", "%");
                studentSpaceProfile = studentSpaceProfile.replaceAll("%2C", ",");
                System.err.println("studentSpaceProfile:" + studentSpaceProfile);
            }
        }
        return studentSpaceProfile;
    }


    /**
     * JSKJ-academyInfo={%22id%22:11%2C%22name%22:%22%E6%96%B0%E7%96%86%E5%BC%80%E6%94%BE%E5%A4%A7%E5%AD%A6%22%2C%22code%22:%22650%22%2C%22pid%22:0%2C%22level%22:%221%22%2C%22enable%22:1%2C%22remark%22:%22%22%2C%22linkman%22:%22%22%2C%22mobile%22:%2213500000000%22%2C%22addr%22:%22%22%2C%22instId%22:11%2C%22logo%22:%22https://filessourcesk.open.com.cn/opensk/0/0/content/20211009/7FE9E33AA2D34B16987CAD8D2D6736D6.png%22%2C%22logoExtra%22:%22https://filessourcesk.open.com.cn/opensk/0/0/content/20211009/1E9FE9A9FDCC45259D9C2D09ACD02130.png%22%2C%22domain%22:%22xjskk.open.com.cn%22%2C%22bigdata%22:1%2C%22bigdataHost%22:%22https://sensordata.open.com.cn/sa?project=kaida_shengkai%22%2C%22isDefault%22:1}; XSKJ-academyInfo={%22id%22:11%2C%22name%22:%22%E6%96%B0%E7%96%86%E5%BC%80%E6%94%BE%E5%A4%A7%E5%AD%A6%22%2C%22code%22:%22650%22%2C%22pid%22:0%2C%22level%22:%221%22%2C%22enable%22:1%2C%22remark%22:%22%22%2C%22linkman%22:%22%22%2C%22mobile%22:%2213500000000%22%2C%22addr%22:%22%22%2C%22instId%22:11%2C%22logo%22:%22https://filessourcesk.open.com.cn/opensk/0/0/content/20211009/7FE9E33AA2D34B16987CAD8D2D6736D6.png%22%2C%22logoExtra%22:%22https://filessourcesk.open.com.cn/opensk/0/0/content/20211009/1E9FE9A9FDCC45259D9C2D09ACD02130.png%22%2C%22domain%22:%22xjskk.open.com.cn%22%2C%22bigdata%22:1%2C%22bigdataHost%22:%22https://sensordata.open.com.cn/sa?project=kaida_shengkai%22%2C%22isDefault%22:1}; username=; pwd=; checked=false; XSKJ-academyId=11; XSKJ-academyName=%E6%96%B0%E7%96%86%E5%B9%BF%E6%92%AD%E7%94%B5%E8%A7%86%E5%A4%A7%E5%AD%A6; XSKJ-ACOUNT-PC=410928199802232739; XSKJ-re_ticket=046ab497-4997-47be-b822-fd98afba2375; XSKJ-Admin-Struct=%257BproductId%253A6%2CstudentId%253A283789%257D; JSKJ-ACCOUNT-PC=lijunj; JSKJ-re_ticket=5c9814a7-0d34-4740-aa34-7a278066b482; JSKJ-expires_in=7199; JSKJ-academyId=11; JSKJ-academyName=undefined; JSKJ-account=lijunj; JSKJ-teacherName=%E6%9D%8E%E4%BF%8A%E6%9D%B0; JSKJ-Admin-Struct=%257BproductId%253A7%2CroleId%253A49%257D; themeColor=primary; JSKJ-teacherId=492; JSKJ-login_timeStamp=1635063055586; sensorsdata2015jssdkcross=%7B%22distinct_id%22%3A%22410928199802232739%22%2C%22first_id%22%3A%22178be8e2eef7db-0d14c2559a7957-c3f3568-3686400-178be8e2ef0be8%22%2C%22props%22%3A%7B%22%24latest_traffic_source_type%22%3A%22%E7%9B%B4%E6%8E%A5%E6%B5%81%E9%87%8F%22%2C%22%24latest_search_keyword%22%3A%22%E6%9C%AA%E5%8F%96%E5%88%B0%E5%80%BC_%E7%9B%B4%E6%8E%A5%E6%89%93%E5%BC%80%22%2C%22%24latest_referrer%22%3A%22%22%7D%2C%22%24device_id%22%3A%22178be8e2eef7db-0d14c2559a7957-c3f3568-3686400-178be8e2ef0be8%22%7D; XSKJ-ticket=0e9ec0be-f817-4369-ac16-9b76699bdc55; XSKJ-login_timeStamp=1635065146510; XSKJ-expires_in=35229; XSKJ-schoolRoleId=283789; XSKJ-studentId=283789; XSKJ-productId=6; XSKJ-ybmStudentStatus=1; XSKJ-roleStudentStatus=1;
     * XSKJ-isOnlyRole=true; _fmdata=o1EESkUj%2Btbn7MKpJCCK3oDWnejodu8JkAvWJcpZ%2B92WdUv7Y0ro1n9f2ApHO%2FOwKlhdKjbsyVCQit%2FBymLvQXby6hmqCKuWA%2FFQl43uKJQ%3D
     * @param set
     * @return
     */
    public static String getStudentSpaceProfile2( Set<Cookie> set){
        String studentSpaceProfile = "";
        for (Cookie c : set) {
            System.err.println(c.getName()+"\t"+c.getValue());
            // XS:学生 JS:教师
             if ("XSKJ-Admin-Struct" .equals(c.getName())) {
           // if ("JSKJ-Admin-Struct" .equals(c.getName())) {
                studentSpaceProfile = c.getValue();
                studentSpaceProfile = studentSpaceProfile.replaceAll("%25", "%");
                studentSpaceProfile = studentSpaceProfile.replaceAll("%2C", ",");
                System.err.println("studentSpaceProfile:" + studentSpaceProfile);
            }
        }
        // fixme
        if(Strings.isNullOrEmpty(studentSpaceProfile)){
            studentSpaceProfile = "%7BproductId%3Acanshu1,studentId%3Acanshu2,academyId%3Acanshu3%7D";
            for (Cookie c : set) {
                String cName = c.getName();
                if ("XSKJ-productId" .equals(cName)) {
                    studentSpaceProfile = studentSpaceProfile.replaceAll("canshu1", c.getValue());
                }
                if ("XSKJ-studentId" .equals(cName)) {
                    studentSpaceProfile = studentSpaceProfile.replaceAll("canshu2", c.getValue());
                }
                if ("XSKJ-academyId" .equals(cName)) {
                    studentSpaceProfile = studentSpaceProfile.replaceAll("canshu3", c.getValue());
                }
            }
        }
        // fixme
        return studentSpaceProfile;
    }

    /**
     * 将cookie里面的XXSKJ-ticket提取出来封装成header里面的参数
     * @param set cookie集合
     * @return authorizati
     */
    public static String getAuthorization( Set<Cookie> set){
        /**
         * sajssdk_2015_cross_new_user=1; JSKJ-academyInfo={%22id%22:11%2C%22name%22:%22%E6%96%B0%E7%96%86%E5%B9%BF%E6%92%AD%E7%94%B5%E8%A7%86%E5%A4%A7%E5%AD%A6%22%2C%22code%22:%22650%22%2C%22pid%22:0%2C%22level%22:%221%22%2C%22enable%22:1%2C%22remark%22:%22%22%2C%22linkman%22:%22%22%2C%22mobile%22:%2213500000000%22%2C%22addr%22:%22%22%2C%22instId%22:11%2C%22logo%22:%22https://oescdn.open.com.cn/testyf/PI/DATA/2019/0906/PIrkqaiDATA20190906155634701.png?Expires=3144556593&OSSAccessKeyId=81kgc0VJPbZ4WnpN&Signature=YZtyaSWEZLWsIVLM57Ggz6WGqVU%253D%22%2C%22logoExtra%22:%22https://resourcepath.oss-cn-beijing.aliyuncs.com/opensk/0/0/content/20200316/D0E996C933FA493693E7FB357F122791.png%22%2C%22domain%22:%22xjskk.open.com.cn%22%2C%22bigdata%22:1%2C%22bigdataHost%22:%22https://sensordata.open.com.cn/sa?project=kaida_shengkai%22%2C%22isDefault%22:1}; username=; pwd=; checked=false; JSKJ-ACCOUNT-PC=liujw; sensorsdata2015jssdkcross=%7B%22distinct_id%22%3A%22liujw%22%2C%22first_id%22%3A%2217aa4112495215-05b17573b62604-6373267-3686400-17aa4112496e8d%22%2C%22props%22%3A%7B%22%24latest_traffic_source_type%22%3A%22%E7%9B%B4%E6%8E%A5%E6%B5%81%E9%87%8F%22%2C%22%24latest_search_keyword%22%3A%22%E6%9C%AA%E5%8F%96%E5%88%B0%E5%80%BC_%E7%9B%B4%E6%8E%A5%E6%89%93%E5%BC%80%22%2C%22%24latest_referrer%22%3A%22%22%7D%2C%22%24device_id%22%3A%2217aa4112495215-05b17573b62604-6373267-3686400-17aa4112496e8d%22%7D; JSKJ-ticket=34ae066e-0fe7-4f5f-9f81-4cdba6aa65dc; JSKJ-re_ticket=d417ecc3-aee2-4750-979b-c85a4df94f7d; JSKJ-login_timeStamp=1626250226537; JSKJ-expires_in=5416; JSKJ-schoolRoleId=61; JSKJ-productId=7; JSKJ-academyId=11; JSKJ-academyName=undefined; JSKJ-isOnlyRole=true; JSKJ-teacherId=1625; JSKJ-account=liujw; JSKJ-teacherName=%E5%88%98%E4%BF%8A%E4%BC%9F; JSKJ-Admin-Struct=%257BproductId%253A7%2CroleId%253A61%257D; themeColor=primary; _fmdata=CoyMDqJorhLch7r%2FweU4yVGpAWUrQB6xFVW3o5IteesjRPpKN8vhGDj1%2BhlM3sBd4ZPSFkululLbzK3tH3Ad4%2Bmu%2F1HBrMFa8aDeuR6%2Fvi0%3D
         */
        String authorizati = "";
        for (Cookie c : set) {
          //  if("XSKJ-ticket".equals(c.getName())){
            if("JSKJ-ticket".equals(c.getName())){
                authorizati = "Bearer "+c.getValue();
            }
        }
        return authorizati;
    }

    public static String getAuthorization2( Set<Cookie> set){
        String authorizati = "";
        for (Cookie c : set) {
              if("XSKJ-ticket".equals(c.getName())){
                authorizati = "Bearer "+c.getValue();
            }
        }
        return authorizati;
    }


    /**
     * 设置编码格式存储list到txt
     *
     * @param path path
     * @param list list
     */

    @SuppressWarnings("resource")
    public static <T> void fileWriteList(String path, List<T> list) {
        if(null == list||list.size()<1){
            return;
        }
        try {
            BufferedWriter bufferedWriter = new BufferedWriter(
                    new OutputStreamWriter(new FileOutputStream(path), StandardCharsets.UTF_8));
//            for (T s : list) {
//                bufferedWriter.write(JSON.toJSONString(s));
//                bufferedWriter.newLine();
//                bufferedWriter.flush();
//            }
            bufferedWriter.write(JSON.toJSONString(list));
            bufferedWriter.close();
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }


    /**
     * 获取单个页面所有的问题
     * @param driver driver
     * @return  List<WebElement>
     */
    public static List<WebElement> getSinglePageQuestionList(WebDriver driver){
        List<WebElement> singlePageQuestion = Lists.newArrayList();
        for(WebElement singleSubject:driver.findElements(By.cssSelector("div[class^='que']"))){
            //que description informationitem answersaved 过滤到题目说明
            String singleSubjectClassName = singleSubject.getAttribute("class");
            if(singleSubjectClassName.contains("description")&&singleSubjectClassName.contains("informationitem")){
                continue;
            }
            String questionId = singleSubject.getAttribute("id");
            // 过滤掉标题题目的   yui_3_17_2_1_1620910258597_362
            // 过滤掉清空我的选择
            if(!questionId.contains("question")||questionId.contains("clearchoice")){
                continue;
            }
            System.err.println("questionId:" + questionId);
            singlePageQuestion.add(singleSubject);
        }
        return singlePageQuestion;
    }


    /**
     * 获取某门课程下的所有的形考任务url
     * @param driver driver
     * @param courseName 课程名称
     * @return  形考任务url
     */
    public static List<String> getCourseTaskUrl(WebDriver driver,String courseName){
        // 形考作业的链接
        List<String> urlTasks = Lists.newArrayList();
        // 找到每个学习栏目
        for (WebElement we : driver.findElements(By.className("media-body"))) {
            switchToFirst(driver);
            // 找到管理学基础
            String mediaTitle = we.findElement(By.className("media-title")).getText();

            if (!mediaTitle.contains(courseName)) {
                continue;
            }
            //点击进入学习的按钮
            WebElement studyButton = we.findElement(By.cssSelector("button[class='btn bg-primary']"));
            studyButton.click();
            switchToLast(driver);
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            // section main aft
            for (WebElement li : driver.findElements(By.cssSelector("li[class='section main aft']"))) {
                // 找到章节的名字
                WebElement sectionNameElement = li.findElement(By.cssSelector("h3[class='sectionname']"));
                if (null == sectionNameElement) {
                    continue;
                }
                String sectionName = sectionNameElement.getText();
                // 形考任务、大作业、课程考核等等
                if (!"形考任务".equals(sectionName)) {
                    continue;
                }
                li.click();
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                for (WebElement task : li.findElements(By.className("activityinstance"))) {
                    String taskName = task.getText();
                    System.err.println("taskName"+taskName);
                    // FIXME
//                    if(Strings.isNullOrEmpty(taskName)||!taskName.contains("形考任务")||!taskName.contains("作业")){
//                        continue;
//                    }
                    if(Strings.isNullOrEmpty(taskName)||!taskName.contains("形考任务")){
                        continue;
                    }
                    System.out.println("taskName::"+taskName);
                    WebElement linkElement = task.findElement(By.className("aalink"));
                    if (linkElement != null) {
                        System.err.println(linkElement.getAttribute("href"));
                        String urlTask = linkElement.getAttribute("href");
                        System.err.println("urlTask:"+urlTask);
                        // 过滤资源文件下载
                        if (urlTask.contains("resource")) {
                            continue;
                        }
                        // 过滤平时行为表现 （如：管理心理学）
                        if (urlTask.contains("mod/assign")) {
                            continue;
                        }
                        urlTasks.add(urlTask);
                    }
                }
            }
        }
        return urlTasks;
    }

    public static List<String> getCourseTaskUrl(String subjectCode) throws IOException {
        //获取模板路径,通过流的方式获取文件可以避免被打成jar包之后无法获取文件路径的异常
        InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream( subjectCode + "/" + subjectCode +".section");
        List<String> list = IOUtils.readLines(inputStream);
        List<String> paths = new ArrayList<>();
        for (String str:list) {
            paths.add(str.split(",")[0]);
        }
        return paths;
    }


    /**
     * 做单选题、多选题和判断题
     * @param driver 驱动
     * @param answerElement 题目Element
     * @param answerType 题目类型
     * @param realAnswers 正确答案
     */
    public static void doExercise(WebDriver driver,WebElement answerElement,String answerType,List<String> realAnswers) throws Exception {
        switch (answerType){
            case "1":
            case "2":
            case "3":
                doChoiceExercise(answerElement,realAnswers);
                break;
            case "5":
                doShortAnswerExercise(driver,answerElement,realAnswers);
                break;
            // 完型填空
            case "6":
              //  doMultiAnswer(driver,answerElement,realAnswers);
                doMultiAnswer(driver,answerElement,realAnswers);
                break;
                // 匹配题目
            case "4":
                doGapFilling(answerElement,realAnswers);
                break;
            case "7":
                doUpload( driver,answerElement,realAnswers);
                break;
            case "10":
                //  doMultiAnswer(driver,answerElement,realAnswers);
                doDdwtosAnswer(driver,answerElement,realAnswers);
                break;
            default:
                throw new Exception("当前题型不支持自动答题！");
        }
    }

    public static void doExercise(WebDriver driver,WebElement answerElement,String answerType, AnswerObject answerObject) throws Exception {
        switch (answerType){
            case "1":
            case "2":
            case "3":
                doChoiceExercise(answerElement,answerObject.getAnswers());
                break;
            case "5":
                doShortAnswerExercise(driver,answerElement,answerObject.getAnswers());
                break;
            // 完型填空
            case "6":
                //  doMultiAnswer(driver,answerElement,realAnswers);
                doMultiAnswer(driver,answerElement,answerObject.getAnswers());
                break;
            // 匹配题目
            case "61":
                //  doMultiAnswer(driver,answerElement,realAnswers);
                doMatchAnswer(driver,answerElement,answerObject);
                break;
            case "4":
                doGapFilling(answerElement,answerObject.getAnswers());
                break;
            case "7":
                doUpload( driver,answerElement,answerObject.getAnswers());
                break;
            case "10":
                //  doMultiAnswer(driver,answerElement,realAnswers);
                doDdwtosAnswer(driver,answerElement,answerObject.getAnswers());
                break;
            default:
                throw new Exception("当前题型不支持自动答题！");
        }
    }

    /**
     * 上传文件
     * @param answerElement
     * @param realAnswers
     */
    private static void doUpload(WebDriver driver ,WebElement answerElement, List<String> realAnswers) {
        try {

            int index = Integer.parseInt(realAnswers.get(0));

            System.err.println("size1:"+ driver.findElements(By.cssSelector("i[class='icon fa fa-list fa-fw ']")).size());
            System.err.println("size2:"+ driver.findElements(By.cssSelector("div[class='dndupload-arrow'")).size());
            driver.findElements(By.cssSelector("i[class='icon fa fa-list fa-fw ']")).get(index).click();
            driver.findElements(By.cssSelector("div[class='dndupload-arrow']")).get(index*2).click();
            Thread.sleep(2000);
            // 选中 选中文件
            for (WebElement we : driver.findElements(By.className("fp-repo-name"))) {
                if (we.getText().trim().equals("上传一个文件")) {
                    we.click();
                }
            }

            Thread.sleep(4000);
            WebElement upload = driver.findElement(By.cssSelector("input[name='repo_upload_file']"));
           // upload.sendKeys(realAnswers.get(1));
            upload.sendKeys("F:\\任务1.docx");
            Thread.sleep(2000);
            // 点击上传
            driver.findElement(By.cssSelector("button[class='fp-upload-btn btn-primary btn']")).click();
            Thread.sleep(2000);
            // 保存更改
//            driver.findElement(By.cssSelector("input[type='submit']")).click();
//            Thread.sleep(500 * 1000);

        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 填空题
     * @param answerElement
     * @param realAnswers
     */
    private static void doGapFilling(WebElement answerElement, List<String> realAnswers) {
        try {
            List<WebElement>inputList =  answerElement.findElements(By.cssSelector("input[class^='form-control']"));
            System.err.println("inputList.size():"+inputList.size());
            for(int i = 0 ;i<inputList.size();i++){
                WebElement input = inputList.get(i);
                input.clear();
                input.sendKeys( realAnswers.get(i));
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 做单选题、多选题和判断题
     * @param answerElement 题目Element
     * @param realAnswers 正确答案
     */
    private static void doChoiceExercise(WebElement answerElement,List<String> realAnswers){

        boolean isSelected = false;
        // 找到每一个选项
        // 针对多选和单选和判断题
        for (WebElement singleAnswerElement : answerElement.
                findElements(By.cssSelector("div[class='r0'],div[class='r1']"))) {
            // 每个答案的文本 p标签 =单选和多选 label标签=判断题
            // FIXME FENGX 06-24 兼容图片
            //   String answerContent = singleAnswerElement.findElement(By.cssSelector("p,label")).getText();
            String answerContent = Util.getAnswer(singleAnswerElement);
            //兼容特殊字符
            answerContent = Util.dealContent(answerContent);
            // 找到单选框或复选框
            WebElement checkboxElement = singleAnswerElement.
                    findElement(By.cssSelector("input[type='checkbox'],input[type='radio']"));
            // 这里的ID是每个选项的ID answerContent是每个选项的内容
            if(checkboxElement.isSelected()){
                isSelected = true;
                checkboxElement.click();
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            if(answerContent.contains("a.")
                    ||answerContent.contains("b.")
                    ||answerContent.contains("c.")
                    ||answerContent.contains("d.")
                    ||answerContent.contains("e.")
                    ||answerContent.contains("f.")
                    ||answerContent.contains("A.")
                    ||answerContent.contains("B.")
                    ||answerContent.contains("C.")
                    ||answerContent.contains("D.")
                    ||answerContent.contains("F.")
            ){
                answerContent = answerContent.substring(2);
                answerContent = answerContent.trim();
            }

            for(String realAnswer:realAnswers){
                if(realAnswer.contains("a.")
                        ||realAnswer.contains("b.")
                        ||realAnswer.contains("c.")
                        ||realAnswer.contains("d.")
                        ||realAnswer.contains("e.")
                        ||realAnswer.contains("f.")
                        ||realAnswer.contains("A.")
                        ||realAnswer.contains("B.")
                        ||realAnswer.contains("C.")
                        ||realAnswer.contains("D.")
                        ||realAnswer.contains("F.")
                ){
                    realAnswer = realAnswer.substring(2);
                    realAnswer = realAnswer.trim();
                }

                if(realAnswer.equals(answerContent)){
                    isSelected = true;
                    if(checkboxElement.isSelected()){
                        continue;
                    }
                    checkboxElement.click();
                }
            }

            boolean selected = false;
            // 7-2 fixme
            for(String realAnswer:realAnswers){
                if(answerContent.contains(realAnswer)){
                    selected = true;
                    if(checkboxElement.isSelected()){
                        continue;
                    }
                    if(!isSelected){
                        checkboxElement.click();
                    }
                }
            }

            // 如果都没选中话 因为图片链接一直再换！！！！
            if(!selected&&answerContent.contains(".png")){
                for(String realAnswer:realAnswers){
                    if(!realAnswer.contains(".png")){
                        continue;
                    }
                    String s1 = realAnswer.substring(realAnswer.lastIndexOf("/"));
                    String s2 = answerContent.substring(answerContent.lastIndexOf("/"));
                    if(s1.equals(s2)){
                        if(checkboxElement.isSelected()){
                            continue;
                        }
                        if(!isSelected){
                            checkboxElement.click();
                        }
                    }
                //    String
                }
            }

            //            if (realAnswers.contains(answerContent)) {
//                // 如果命中，就点击勾选
//                if(checkboxElement.isSelected()){
//                    continue;
//                }
//                checkboxElement.click();
            // 7-2 fixme


//            if (realAnswers.contains(answerContent)) {
//                // 如果命中，就点击勾选
//                if(checkboxElement.isSelected()){
//                    continue;
//                }
//                checkboxElement.click();
//            }

        }
    }

//    private static void   doMultiAnswer(WebDriver driver,WebElement answerElement,List<String> realAnswers){
//
//        try {
//            List<WebElement> inputListElement = answerElement.findElements(By.tagName("input"));
//            System.err.println("inputListElement:" + inputListElement.size());
//            // 应对单个题目的多选
//            int i = 0;
//            for (WebElement input : inputListElement) {
//                // form-control mb-1
//                if(!input.getAttribute("class").contains("form-control")){
//                    continue;
//                }
//                input.clear();
//                String answer = realAnswers.get(i);
//                i++;
//                input.sendKeys(answer);
//                input.sendKeys("1");
//            }
//        }catch (Exception e){
//            e.printStackTrace();
//        }
//        //切换回主页面
//        driver.switchTo().defaultContent();
//    }

    // 拖拉拽
    private static void   doDdwtosAnswer(WebDriver driver,WebElement answerElement ,List<String> answers){


        try {

            int index = 0;
            for (WebElement spanWe:answerElement.findElements(By.cssSelector("span[class$='active group1']"))){
               for (WebElement dragWe:answerElement.findElements(By.cssSelector("span[class^='draghome ']"))){
                   if(answers.get(index).equals(Util.dealContent(dragWe.getText()))){
                       new Actions(driver).dragAndDrop(dragWe, spanWe).perform();
                       index++;
                       break;
                   }
               }



            }


            List<WebElement> selectList =  answerElement.findElements(By.cssSelector("select[class^='select custom-select']"));


        }catch (Exception e){
            // e.printStackTrace();
        }
        //切换回主页面
        driver.switchTo().defaultContent();
    }

    private static void   doMatchAnswer(WebDriver driver,WebElement answerElement ,AnswerObject answerObject){

        List<String>  realAnswers = Lists.newArrayList();

        Map<String,String> answers = Maps.newLinkedHashMap();

        for(int i = 0;i<answerObject.getItems().size();i++){
            System.err.println("i="+i+" itemsL"+answerObject.getItems().get(i).getContent()+"   content"+answerObject.getAnswers().get(i));
            answers.put(answerObject.getItems().get(i).getContent(),answerObject.getAnswers().get(i));
        }



        for(WebElement trWe:answerElement. findElements(By.cssSelector("tr[class='r0'],tr[class='r1']"))){
           String pText = trWe.findElement(By.cssSelector("td[class='text']")).getText();
           realAnswers.add(answers.get(pText));
        }



        try {
            // List<WebElement>inputList =  singleSubject.findElements(By.cssSelector("input[class^='select custom-select']"));
            List<WebElement>inputList =  answerElement.findElements(By.cssSelector("input[class^='form-control']"));
            System.err.println("inputList.size():"+inputList.size());
            for(int i = 0 ;i<inputList.size();i++){
                inputList.get(i).sendKeys( realAnswers.get(i));
            }
        }catch (Exception e){
            // e.printStackTrace();
        }

        try {
            List<WebElement> selectList =  answerElement.findElements(By.cssSelector("select[class^='select custom-select']"));
            System.err.println("selectList.size():"+selectList.size());
            for(int i = 0 ;i<selectList.size();i++){
                Select select = new Select(selectList.get(i));
                String answer =realAnswers.get(i);
                String value = DataConvert.get(answer);
                if(null!=value){
                    select.selectByValue(DataConvert.get(realAnswers.get(i)));
                }else {
                    List<WebElement>  options = selectList.get(i).findElements(By.tagName("option"));
                    System.err.println("??:options.size()"+options.size());
                    int k = 0;

                    for(WebElement option:options){

                        if(!Strings.isNullOrEmpty(option.getText())&&
                                Util.dealContent(option.getText()).equals(Util.dealContent(answer))){
                            System.err.println("k="+k+"  "+option.getText());
                            // select.selectByValue(String.valueOf(--k));
                            select.selectByValue(String.valueOf(k));
                        }else {
                            k++;
                        }
                    }
                }
            }

        }catch (Exception e){
            // e.printStackTrace();
        }
        //切换回主页面
        driver.switchTo().defaultContent();
    }


    private static void   doMultiAnswer(WebDriver driver,WebElement answerElement,List<String> realAnswers ){


        try {
            // List<WebElement>inputList =  singleSubject.findElements(By.cssSelector("input[class^='select custom-select']"));
            List<WebElement>inputList =  answerElement.findElements(By.cssSelector("input[class^='form-control']"));
            System.err.println("inputList.size():"+inputList.size());
            for(int i = 0 ;i<inputList.size();i++){
                inputList.get(i).clear();
                Thread.sleep(200);
                inputList.get(i).sendKeys( realAnswers.get(i));
            }
        }catch (Exception e){
            // e.printStackTrace();
        }

        try {
            List<WebElement> selectList =  answerElement.findElements(By.cssSelector("select[class^='select custom-select']"));
            System.err.println("selectList.size():"+selectList.size());
            for(int i = 0 ;i<selectList.size();i++){
                Select select = new Select(selectList.get(i));
                String answer =realAnswers.get(i);
                String value = DataConvert.get(answer);
                if(null!=value){
                    select.selectByValue(DataConvert.get(realAnswers.get(i)));
                }else {
                    List<WebElement>  options = selectList.get(i).findElements(By.tagName("option"));
                    System.err.println("??:options.size()"+options.size());
                    int k = 0;
                    boolean containSelect = false;
                    for(WebElement option:options){
                        if(!Strings.isNullOrEmpty(option.getText())&&option.getText().contains("选择")){
                            containSelect = true;
                        }
                        if(!Strings.isNullOrEmpty(option.getText())&&
                                Util.dealContent(option.getText()).equals(Util.dealContent(answer))){
                          //  select.selectByValue(String.valueOf(--k));
                            if(containSelect){
                                select.selectByValue(String.valueOf(k));
                            }else {
                                select.selectByValue(String.valueOf(--k));
                            }
                        }else {
                            k++;
                        }
                    }
                }
            }

        }catch (Exception e){
            // e.printStackTrace();
        }
        //切换回主页面
        driver.switchTo().defaultContent();
    }

    /**
     * 做单选题、多选题和判断题
     * @param driver 驱动
     * @param answerElement 题目Element
     * @param realAnswers 正确答案
     */
    private static void doShortAnswerExercise(WebDriver driver,WebElement answerElement,List<String> realAnswers) throws UnsupportedEncodingException {
       /* WebElement textArea = findByTagName(answerElement, "textarea");
        WebElement iframe = findByTagName(answerElement, "iframe");*/
        System.err.println("doShortAnswerExercise:::::::::11111111111111111111");
        String answer = realAnswers.get(0);
      try{
          WebElement element = answerElement.findElement(By.tagName("iframe"));
          System.out.println(element.toString());
          driver.switchTo().frame(element);
          WebElement webElement = driver.findElement(By.tagName("body"));
          //answer = new String(answer.getBytes(),"utf-8");
          if (null != webElement) {
              webElement.clear();
              webElement.sendKeys(answer);
          }
          //切换回主页面
          driver.switchTo().defaultContent();
      }catch (Exception e){
          answerElement.findElement(By.tagName("textarea")).sendKeys(answer);
      }



/*
        if (null != textArea && iframe != null) {
            String js = "document.getElementById('"+iframe.getAttribute("id")+"').contentWindow.document.body.innerText = '"+answer+ "'";
            ((JavascriptExecutor) driver).executeScript(js);
            System.out.println(realAnswers.get(0));
            */
        /*textArea.sendKeys(realAnswers.get(0));*//*

        }
*/
       /* WebElement textArea = findByClassName(answerElement,"mceContentBody");
        textArea.sendKeys(realAnswers.get(0));*/
    }


    public static WebElement findByClassName(WebElement we, String className) {
        WebElement webElement = null;
        try {
            webElement = we.findElement(By.className(className));
        } catch (Exception ignored) {
            return null;
        }
        return webElement;
    }

    public static WebElement findByClassName(WebDriver driver, String className) {
        WebElement webElement = null;
        try {
            webElement = driver.findElement(By.className(className));
        } catch (Exception ignored) {
            return null;
        }
        return webElement;
    }

    public static WebElement findByCssSelector(WebElement we, String cssSelector) {
        WebElement webElement = null;
        try {
            webElement = we.findElement(By.cssSelector(cssSelector));
        } catch (Exception ignored) {
            return null;
        }
        return webElement;
    }

    public static List<WebElement> findAllByCssSelector(WebElement we, String cssSelector) {
        List<WebElement > list;
        try {
            list = we.findElements(By.cssSelector(cssSelector));
        } catch (Exception ignored) {
            return null;
        }
        return list;
    }
    public static WebElement findByTagName(WebElement we, String tagName) {
        WebElement webElement = null;
        try {
            webElement = we.findElement(By.tagName(tagName));
        } catch (Exception ignored) {
            return null;
        }
        return webElement;
    }

    public static List<WebElement> findAllByTagName(WebElement we, String tagName) {
        List<WebElement> webElements = null;
        try {
            webElements = we.findElements(By.tagName(tagName));
        } catch (Exception ignored) {
            return null;
        }
        return webElements;
    }

    public static WebElement findByCssSelector(WebDriver driver, String cssSelector) {
        WebElement webElement = null;
        try {
            webElement = driver.findElement(By.cssSelector(cssSelector));
        } catch (Exception ignored) {
            return null;
        }
        return webElement;
    }


    // 是否有下一页
    public static WebElement findNextPage(WebDriver we) {
        try {
            return we.findElement(By.cssSelector("input[value='下一页']"));
        } catch (Exception e) {
            return null;
        }
    }



    // 回到做作业首页
    public static void goHomePageIndex(WebDriver driver){
        String homeworkUrl = driver.getCurrentUrl();
        System.out.println("homeworkUrl:" + homeworkUrl);
        if (homeworkUrl.contains("page=")) {
            homeworkUrl = homeworkUrl.substring(0, homeworkUrl.indexOf("page="))
                    + "page=0"
                    + homeworkUrl.substring(homeworkUrl.indexOf("page=") + 6);
        }
        driver.get(homeworkUrl);
    }

    public static String getTitle(WebElement element) {
        try{
            WebElement qTitleElement = element.findElement(By.className("qtext"));
            String title = qTitleElement.getText();
            title = Util.dealContent(title);
          //  List<WebElement> imgList = qTitleElement.findElements(By.tagName("img"));
            List<WebElement> imgList =Util.findAllByTagName(qTitleElement,"img");
            if (imgList!=null&&imgList.size() > 0) {
                List<String> imgUrlList = Lists.newArrayList();
                for (WebElement imgElement : imgList) {
                    imgUrlList.add(imgElement.getAttribute("src").trim());
                }
                Collections.sort(imgUrlList);
                String imgUrl = StringUtils.join("|", imgUrlList);
                title += imgUrl;
            }
            return title;
        }catch (Exception e){
            try {
                // fixme 12-28 新增了一些，会导致之前获取的title无效了！！！！
                // 如果没有qtext 判断是填空题：获取全量：
                return  element.findElement(By.cssSelector("div[class='formulation clearfix']")).getText();
            }catch (Exception e1){
                return element.getText();
            }
        }
    }

    // 标题的title
    public static String getLmsTitle(WebElement summaryWe,boolean isTitle) {
        try{
            String title;
            if(isTitle){
                StringBuilder titleSb = new StringBuilder();
                for(WebElement ngWe:summaryWe.findElements(By.cssSelector("*[class$='ng-scope']"))){
                    // 过滤掉题目的序号
                    if(!Strings.isNullOrEmpty(ngWe.getAttribute("ng-if"))){
                        continue;
                    }
                    titleSb.append(ngWe.getText());
                }

                // type = 8
                    for(WebElement descWe:summaryWe.findElements(By.cssSelector("div[class='content-center desc']"))){
                        System.err.println("descWe.getText():"+descWe.getText());
                        titleSb.append(descWe.getText());
                    }



                 title = titleSb.toString();
                title = Util.dealContent(title);
            }else {
                // 每个选项的title
              //  title= summaryWe.getText();
                title=  Util.dealContent(summaryWe.getText());
            }

            List<WebElement> imgList =Util.findAllByTagName(summaryWe,"img");
            if (imgList!=null&&imgList.size() > 0) {
                List<String> imgUrlList = Lists.newArrayList();
                for (WebElement imgElement : imgList) {
                    imgUrlList.add(imgElement.getAttribute("src").trim());
                }
                Collections.sort(imgUrlList);
                String imgUrl = StringUtils.join("|", imgUrlList);
                title += imgUrl;
            }
            return title;
        }catch (Exception e){
//            try {
//                // fixme 12-28 新增了一些，会导致之前获取的title无效了！！！！
//                // 如果没有qtext 判断是填空题：获取全量：
//                return  element.findElement(By.cssSelector("div[class='formulation clearfix']")).getText();
//            }catch (Exception e1){
//                return element.getText();
//            }
            return "";
        }
    }




    public static String getAnswer(WebElement singleAnswerElement) {

        //    WebElement element = singleAnswerElement.findElement(By.cssSelector("div[class='flex-fill ml-1']"));
        String answerContent;
        WebElement pElement = null;
        try {
            //    pElement = element.findElement(By.cssSelector("p,label"));
            pElement = singleAnswerElement.findElement(By.cssSelector("p,label"));
        } catch (Exception e) {
        }
        if (null != pElement) {
            answerContent = pElement.getText();
        } else {
            //   answerContent = element.getText();
            answerContent = singleAnswerElement.getText();
        }
        answerContent = Util.dealContent(answerContent);

        List<WebElement> imgList = singleAnswerElement.findElements(By.tagName("img"));
        if (imgList.size() > 0) {
            List<String> imgUrlList = Lists.newArrayList();
            for (WebElement imgElement : imgList) {
                imgUrlList.add(imgElement.getAttribute("src").trim());
            }
            Collections.sort(imgUrlList);
            String imgUrl = StringUtils.join("|", imgUrlList);
            answerContent += imgUrl;
        }
        return answerContent;
    }

    /**
     * 进入学习章节
     */
    public static void clickCourseTaskUrl(WebDriver driver, String courseName) {
        // 形考作业的链接
        List<String> urlTasks = Lists.newArrayList();
        // 找到每个学习栏目
        for (WebElement we : driver.findElements(By.className("media-body"))) {
            switchToFirst(driver);
            // 找到管理学基础
            String mediaTitle = we.findElement(By.className("media-title")).getText();
            System.err.println("mediaTitle:" + mediaTitle);

            if (!mediaTitle.contains(courseName)) {
                continue;
            }
            // 点击进入学习的按钮
            WebElement studyButton = we.findElement(By.cssSelector("button[class='btn bg-primary']"));
            studyButton.click();
            switchToLast(driver);
            break;
        }
    }

    public static String dealContent(String content) {
        content = content.trim();
        content = content.replace("\\C","");
        //去掉全角空格
        while (content.startsWith("　")) {
            content = content.substring(1).trim();
        }
        while (content.endsWith("　")) {
            content = content.substring(0, content.length() - 1).trim();
        }
        return content;
    }

    /**
     * 校验视频是否观看完成  如果作业完成了 视频肯定也完成了 反之就是没有完成。
     * @param subjectName subjectName
     * @param userName userName
     * @param workNums  作业个数
     * @return
     */
    public static boolean checkCompleteVideo(String subjectName,String userName,int workNums){
//        boolean isComplete = false;
//      try{
//        //  String filePath = "E:\\answerInfo\\"+subjectName+"\\"+userName+".txt";
//          String filePath = "libs//answerInfo//"+subjectName+"//"+userName+".txt";
//          File userCompleteInfoFile = new File(filePath);
//          InputStream inputStream = new FileInputStream(userCompleteInfoFile);
//          String completeInfoStr = IOUtils.toString(inputStream,"UTF-8");
//          List<CompleteInfo> completeInfoList = JSONObject.parseArray(completeInfoStr, CompleteInfo.class);
//          if(null!=completeInfoList){
//              if(completeInfoList.size()==workNums){
//                  isComplete = true;
//              }
//              for(CompleteInfo info:completeInfoList){
//                  if ("没有这门课程！".equals(info.getSummary())) {
//                      isComplete = true;
//                  }
//              }
//          }
//
//
//      }catch (Exception e){
//          e.printStackTrace();
//      }
//      return isComplete;
        String rootPath = "libs//answerInfo//";
        return checkCompleteVideo(rootPath,subjectName,userName,workNums);
    }

    public static boolean checkCompleteVideo(String subjectName,String userName,int workNums,String teacher){

        String rootPath = "libs//answerInfo//";
        return checkCompleteVideo(rootPath+teacher+"//",subjectName,userName,workNums);
    }

    public static boolean checkCompleteVideo(String rootPath,String subjectName,String userName,int workNums){
        boolean isComplete = false;
        try{
            //  String filePath = "E:\\answerInfo\\"+subjectName+"\\"+userName+".txt";
            String filePath = rootPath +subjectName+"//"+userName+".txt";
            File userCompleteInfoFile = new File(filePath);
            InputStream inputStream = new FileInputStream(userCompleteInfoFile);
            String completeInfoStr = IOUtils.toString(inputStream,"UTF-8");
            List<CompleteInfo> completeInfoList = JSONObject.parseArray(completeInfoStr, CompleteInfo.class);
            System.err.println("completeInfoListSize:"+completeInfoList.size());
            System.err.println("workNums:"+workNums);
            if(null!=completeInfoList){
//                if(completeInfoList.size()==workNums){
//                    isComplete = true;
//                }
                // TODO 2022-06-06
//                if(completeInfoList.size()>=workNums){
//                    isComplete = true;
//                }
//                for(CompleteInfo info:completeInfoList){
//                    if ("没有这门课程！".equals(info.getSummary())) {
//                        isComplete = true;
//                    }
//                }
                // TODO 2022-06-06
                Set<String> haveCompleteHomeWorkUrlSet = Sets.newHashSet();
                for(CompleteInfo info:completeInfoList){
                    if ("没有这门课程！".equals(info.getSummary())) {
                        continue;
                    }
                  if(info.isComplete()){
                      haveCompleteHomeWorkUrlSet.add(info.getHomeworkUrl());
                  }
                }
                if(haveCompleteHomeWorkUrlSet.size()>=workNums){
                    isComplete = true;
                }
            }


        }catch (Exception e){
            e.printStackTrace();
        }
        return isComplete;
    }

    public static void clickLmsCourse(WebDriver driver,String courseName){
        for (WebElement we : driver.findElements(By.tagName("a"))) {
            String textContent = we.getText();
            if (textContent.contains("去学习")) {
                we.click();
                break;
            }
        }

        Util.switchToLast(driver);
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        driver.close();
        Util.switchToFirst(driver);

        boolean isFind = false;

        List<WebElement> courseWeList;
        int index = 1;
        while (!isFind) {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            courseWeList = driver.findElements(By.cssSelector("div[class='ouchnPc_index_course_div']"));
            for (WebElement we : courseWeList) {
                String textContent = we.getText();
               // System.err.println("text111:" + textContent);
                if (textContent.contains(courseName)) {
                    we.findElement(By.tagName("a")).click();
                    isFind = true;
                    break;
                }
            }
            if (!isFind) {
                index++;
              //  System.err.println("=====没找到================");
                for(WebElement li:driver.findElements(By.cssSelector("li[class='number']"))){
                    if(li.getText().equals(String.valueOf(index))){
                        li.click();
                        break;
                    }
                }

            }
        }
    }


}
